const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const ProgressBarPlugin = require("progress-bar-webpack-plugin");
const webpack = require("webpack");

const BASE_PATH = path.resolve(__dirname, "src");

try {
  require.resolve("react/jsx-runtime");
} catch (e) {
  console.log("无法加载", e);
}

let env = process.env.NODE_ENV;
if (!env) {
  env = process.env.NODE_ENV = "development";
}

console.log(`当前${env}环境`);

const config = {
  entry: path.resolve(BASE_PATH, "index.tsx"),
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "js/main.[hash:8].bundle.js",
    chunkFilename: "js/[name].[chunkhash:8].chunk.js",
    hashFunction: "sha256",
  },
  mode: "development",
  devtool: "source-map",
  resolve: {
    alias: {
      "@": BASE_PATH,
    },
    extensions: [".tsx", ".ts", ".jsx", ".js", ".less", ".css", ".json"],
  },
  module: {
    rules: [
      {
        test: /\.(jsx?|tsx?)$/,
        exclude: /node_modules/,
        loader: "babel-loader",
        options: {
          babelrc: false,
          configFile: false,
          presets: [
            [
              "babel-preset-react-app",
              {
                runtime: "automatic",
              },
            ],
          ],
        },
      },
      {
        test: /\.css$/,
        use: [
          env == "production"
            ? MiniCssExtractPlugin.loader
            : require.resolve("style-loader"),
          {
            loader: "css-loader",
            options: {
              modules: {
                localIdentName: "[local]-[hash:base64:5]",
              },
            },
          },
        ],
        sideEffects: true,
      },
      {
        test: /(?<!module)\.less$/,
        use: [
          env == "production"
            ? MiniCssExtractPlugin.loader
            : require.resolve("style-loader"),
          "css-loader",
          "less-loader",
        ],
        sideEffects: true,
      },
      {
        test: /\.module\.less$/,
        use: [
          env == "production"
            ? {
                loader: MiniCssExtractPlugin.loader,
                options: {
                  hmr: false,
                },
              }
            : require.resolve("style-loader"),
          {
            loader: "css-loader",
            options: {
              modules: {
                localIdentName: "[local]-[hash:base64:5]",
              },
            },
          },
          "less-loader",
        ],
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      inject: true,
      filename: "index.html",
      template: `public/${env === "production" ? "index" : "dev"}.html`,
    }),
    new webpack.DefinePlugin({
      ENV: JSON.stringify(env),
    }),
    new ProgressBarPlugin(),
  ],
};

module.exports = config;
